import 'package:flutter/material.dart';
import 'package:flutter_ohos_sqflite_demo/database_helper.dart';
import 'package:intl/intl.dart';

import 'todo.dart';

void main() => runApp(TodoApp());

class TodoApp extends StatelessWidget {
  const TodoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Todo List',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: TodoListPage(),
    );
  }
}

class TodoListPage extends StatefulWidget {
  const TodoListPage({super.key});

  @override
  State<TodoListPage> createState() => _TodoListPageState();
}

class _TodoListPageState extends State<TodoListPage> {
  final DatabaseHelper _dbHelper = DatabaseHelper();
  late Future<List<Todo>> _todos;

  @override
  void initState() {
    super.initState();
    _refreshTodos();
  }

  void _refreshTodos() {
    setState(() {
      _todos = _dbHelper.getTodos();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Todo List'),
        actions: [
          IconButton(
            onPressed: () {
              _showAddTodoDialog();
            },
            icon: const Icon(Icons.add),
          )
        ],
      ),
      body: FutureBuilder<List<Todo>>(
        future: _todos,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          if (snapshot.hasError) {
            return Center(
              child: Text('Error: ${snapshot.error}'),
            );
          }
          final todos = snapshot.data!;
          return todos.isEmpty
              ? const Center(
                  child: Text('No todos found!\nTap + to add new'),
                )
              : ListView.separated(
                  padding: const EdgeInsets.all(16),
                  separatorBuilder: (context, index) =>
                      const SizedBox(height: 12),
                  itemCount: todos.length,
                  itemBuilder: (context, index) {
                    final todo = todos[index];
                    return _buildTodoItem(todo);
                  });
        },
      ),
    );
  }
  Widget _buildTodoItem(Todo todo) {
    return Dismissible(
      key: Key(todo.id.toString()),
      background: Container(color: Colors.red),
      confirmDismiss: (_) async {
        return await showDialog(
          context: context,
          builder: (ctx) => AlertDialog(
            title: Text('Confirm Delete'),
            content: Text('Delete this todo permanently?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(ctx, false),
                child: Text('Cancel'),
              ),
              TextButton(
                onPressed: () => Navigator.pop(ctx, true),
                child: Text('Delete', style: TextStyle(color: Colors.red)),
              ),
            ],
          ),
        );
      },
      onDismissed: (_) async {
        await _dbHelper.deleteTodo(todo.id!);
        _refreshTodos();
      },
      child: Card(
        elevation: 2,
        child: ListTile(
          title: Text(
            todo.title,
            style: TextStyle(
              decoration: todo.isDone
                  ? TextDecoration.lineThrough
                  : TextDecoration.none,
              color: todo.isDone ? Colors.grey : null,
            ),
          ),
          subtitle: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (todo.description.isNotEmpty)
                Padding(
                  padding: EdgeInsets.only(top: 4),
                  child: Text(todo.description),
                ),
              Padding(
                padding: EdgeInsets.only(top: 8),
                child: Text(
                  DateFormat('MMM dd, yyyy').format(todo.date),
                  style: TextStyle(color: Colors.blue),
                ),
              ),
            ],
          ),
          trailing: Checkbox(
            value: todo.isDone,
            onChanged: (value) async {
              final updatedTodo = Todo(
                id: todo.id,
                title: todo.title,
                description: todo.description,
                date: todo.date,
                isDone: value!,
              );
              await _dbHelper.updateTodo(updatedTodo);
              _refreshTodos();
            },
          ),
          onTap: () => _showEditTodoDialog(todo),
        ),
      ),
    );
  }


  void _showAddTodoDialog() => _showTodoDialog(isEditing: false);
  void _showEditTodoDialog(Todo todo) => _showTodoDialog(todo: todo, isEditing: true);

  void _showTodoDialog({Todo? todo, required bool isEditing}) {
    final titleController = TextEditingController(text: todo?.title ?? '');
    final descController = TextEditingController(text: todo?.description ?? '');
    DateTime selectedDate = todo?.date ?? DateTime.now();

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(isEditing ? 'Edit Todo' : 'New Todo'),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: titleController,
                  decoration: InputDecoration(
                    labelText: 'Title',
                    border: OutlineInputBorder(),
                  ),
                  autofocus: true,
                ),
                SizedBox(height: 16),
                TextField(
                  controller: descController,
                  decoration: InputDecoration(
                    labelText: 'Description (optional)',
                    border: OutlineInputBorder(),
                  ),
                  maxLines: 3,
                ),
                SizedBox(height: 16),
                Row(
                  children: [
                    Icon(Icons.calendar_today, size: 20),
                    SizedBox(width: 8),
                    Text(
                      DateFormat('MMM dd, yyyy').format(selectedDate),
                      style: TextStyle(fontSize: 16),
                    ),
                    Spacer(),
                    TextButton(
                      child: Text('Change Date'),
                      onPressed: () async {
                        final pickedDate = await showDatePicker(
                          context: context,
                          initialDate: selectedDate,
                          firstDate: DateTime(2000),
                          lastDate: DateTime(2100),
                        );
                        if (pickedDate != null) {
                          selectedDate = pickedDate;
                          (context as Element).markNeedsBuild();
                        }
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('Cancel'),
            ),
            ElevatedButton(
              onPressed: () async {
                if (titleController.text.trim().isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Title cannot be empty!')),
                  );
                  return;
                }

                final newTodo = Todo(
                  id: todo?.id,
                  title: titleController.text.trim(),
                  description: descController.text.trim(),
                  date: selectedDate,
                  isDone: todo?.isDone ?? false,
                );

                if (isEditing) {
                  await _dbHelper.updateTodo(newTodo);
                } else {
                  await _dbHelper.insertTodo(newTodo);
                }

                _refreshTodos();
                Navigator.pop(context);
              },
              child: Text(isEditing ? 'Save' : 'Add'),
            ),
          ],
        );
      },
    );
  }
}
